﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tum.CollabXT.DocxGen
{
    public class Tree<T> : TreeItem<T>
    {
        public override T Value
        {
            get
            {
                return default(T);
            }
            set
            {
                throw new InvalidOperationException();
            }
        }

        public Tree()
            : base()
        { }
    }

    public class TreeItem<T>
    {
        public virtual T Value
        {
            get;
            set;
        }

        public TreeItem<T>[] Children
        {
            get
            {
                return _ChildList.ToArray();
            }
        }
        private List<TreeItem<T>> _ChildList = new List<TreeItem<T>>();

        public TreeItem<T> Parent
        {
            get;
            private set;
        }


        protected TreeItem()
        {
            if (!(this is Tree<T>))
                throw new InvalidOperationException();
        }

        private TreeItem(TreeItem<T> parent)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");
            Parent = parent;
        }


        public TreeItem<T> AppendChild(T childValue)
        {
            TreeItem<T> newItem = new TreeItem<T>(this);
            newItem.Value = childValue;
            _ChildList.Add(newItem);
            return newItem;
        }

        public TreeItem<T> FindChild(T childValue)
        {
            foreach(var c in _ChildList)
            {
                if((c.Value == null && childValue == null) || c.Value.Equals(childValue))
                    return c;
            }
            return null;
        }

        public bool RemoveChild(TreeItem<T> child)
        {
            return _ChildList.Remove(child);
        }

        public bool RemoveChild(T childValue)
        {
            var r = FindChild(childValue);
            if (r != null)
                return RemoveChild(r);
            return false;
        }
    }
}
